/**
 * API 使用示例
 * 展示如何在 Vue 组件中使用各个 API 模块
 */

import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'

// ============ 认证相关示例 ============

/**
 * 用户登录示例
 */
export const useAuthLogin = () => {
  const loading = ref(false)
  
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await api.auth.login(credentials)
      ElMessage.success('登录成功')
      return response
    } catch (error) {
      ElMessage.error('登录失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  return { login, loading }
}

/**
 * 获取当前用户信息示例
 */
export const useCurrentUser = () => {
  const user = ref(null)
  const loading = ref(false)
  
  const fetchCurrentUser = async () => {
    loading.value = true
    try {
      user.value = await api.auth.getCurrentUser()
    } catch (error) {
      ElMessage.error('获取用户信息失败')
    } finally {
      loading.value = false
    }
  }
  
  onMounted(() => {
    fetchCurrentUser()
  })
  
  return { user, loading, fetchCurrentUser }
}

// ============ 用户管理示例 ============

/**
 * 用户列表管理示例
 */
export const useUserManagement = () => {
  const users = ref([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
  })
  
  const searchForm = reactive({
    keyword: '',
    role: '',
    status: ''
  })
  
  const fetchUsers = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        pageSize: pagination.pageSize,
        ...searchForm
      }
      const response = await api.users.getUsers(params)
      users.value = response.list
      pagination.total = response.total
    } catch (error) {
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const createUser = async (userData) => {
    try {
      await api.users.createUser(userData)
      ElMessage.success('创建用户成功')
      fetchUsers() // 刷新列表
    } catch (error) {
      ElMessage.error('创建用户失败')
    }
  }
  
  const updateUser = async (userId, userData) => {
    try {
      await api.users.updateUser(userId, userData)
      ElMessage.success('更新用户成功')
      fetchUsers() // 刷新列表
    } catch (error) {
      ElMessage.error('更新用户失败')
    }
  }
  
  const deleteUser = async (userId) => {
    try {
      await api.users.deleteUser(userId)
      ElMessage.success('删除用户成功')
      fetchUsers() // 刷新列表
    } catch (error) {
      ElMessage.error('删除用户失败')
    }
  }
  
  onMounted(() => {
    fetchUsers()
  })
  
  return {
    users,
    loading,
    pagination,
    searchForm,
    fetchUsers,
    createUser,
    updateUser,
    deleteUser
  }
}

// ============ 站点管理示例 ============

/**
 * 站点列表管理示例
 */
export const useStationManagement = () => {
  const stations = ref([])
  const loading = ref(false)
  
  const fetchStations = async (params = {}) => {
    loading.value = true
    try {
      const response = await api.stations.getStations(params)
      stations.value = response.list
      return response
    } catch (error) {
      ElMessage.error('获取站点列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const getAvailableStations = async () => {
    try {
      return await api.stations.getAvailableStations()
    } catch (error) {
      ElMessage.error('获取可用站点失败')
      return []
    }
  }
  
  return {
    stations,
    loading,
    fetchStations,
    getAvailableStations
  }
}

// ============ 物品管理示例 ============

/**
 * 物品列表管理示例
 */
export const useItemManagement = () => {
  const items = ref([])
  const categories = ref([])
  const loading = ref(false)
  
  const fetchItems = async (params = {}) => {
    loading.value = true
    try {
      const response = await api.items.getItems(params)
      items.value = response.list
      return response
    } catch (error) {
      ElMessage.error('获取物品列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const fetchCategories = async () => {
    try {
      categories.value = await api.items.getCategories()
    } catch (error) {
      ElMessage.error('获取分类列表失败')
    }
  }
  
  const createItem = async (itemData) => {
    try {
      await api.items.createItem(itemData)
      ElMessage.success('创建物品成功')
      return true
    } catch (error) {
      ElMessage.error('创建物品失败')
      return false
    }
  }
  
  const updateItem = async (itemId, itemData) => {
    try {
      await api.items.updateItem(itemId, itemData)
      ElMessage.success('更新物品成功')
      return true
    } catch (error) {
      ElMessage.error('更新物品失败')
      return false
    }
  }
  
  onMounted(() => {
    fetchCategories()
  })
  
  return {
    items,
    categories,
    loading,
    fetchItems,
    createItem,
    updateItem
  }
}

// ============ 订单管理示例 ============

/**
 * 订单管理示例
 */
export const useOrderManagement = () => {
  const orders = ref([])
  const loading = ref(false)
  
  const fetchOrders = async (params = {}) => {
    loading.value = true
    try {
      const response = await api.orders.getOrders(params)
      orders.value = response.list
      return response
    } catch (error) {
      ElMessage.error('获取订单列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const createOrder = async (orderData) => {
    try {
      const response = await api.orders.createOrder(orderData)
      ElMessage.success('创建订单成功')
      return response
    } catch (error) {
      ElMessage.error('创建订单失败')
      throw error
    }
  }
  
  const updateOrderStatus = async (orderId, status, notes = '') => {
    try {
      await api.orders.updateOrderStatus(orderId, status, notes)
      ElMessage.success('订单状态更新成功')
      fetchOrders() // 刷新列表
    } catch (error) {
      ElMessage.error('订单状态更新失败')
    }
  }
  
  const calculatePrice = async (items) => {
    try {
      return await api.orders.calculateOrderPrice(items)
    } catch (error) {
      ElMessage.error('价格计算失败')
      return null
    }
  }
  
  return {
    orders,
    loading,
    fetchOrders,
    createOrder,
    updateOrderStatus,
    calculatePrice
  }
}

/**
 * 我的订单（客户视角）示例
 */
export const useMyOrders = () => {
  const myOrders = ref([])
  const loading = ref(false)
  
  const fetchMyOrders = async (params = {}) => {
    loading.value = true
    try {
      const response = await api.orders.getMyOrders(params)
      myOrders.value = response.list
      return response
    } catch (error) {
      ElMessage.error('获取我的订单失败')
    } finally {
      loading.value = false
    }
  }
  
  onMounted(() => {
    fetchMyOrders()
  })
  
  return {
    myOrders,
    loading,
    fetchMyOrders
  }
}

// ============ 物流管理示例 ============

/**
 * 物流管理示例
 */
export const useLogisticsManagement = () => {
  const logistics = ref([])
  const loading = ref(false)
  
  const fetchLogistics = async (params = {}) => {
    loading.value = true
    try {
      const response = await api.logistics.getLogistics(params)
      logistics.value = response.list
      return response
    } catch (error) {
      ElMessage.error('获取物流信息失败')
    } finally {
      loading.value = false
    }
  }
  
  const getTrackingInfo = async (orderId) => {
    try {
      return await api.logistics.getTrackingInfo(orderId)
    } catch (error) {
      ElMessage.error('获取物流追踪信息失败')
      return null
    }
  }
  
  const dispatchVehicle = async (logisticsId, dispatchData) => {
    try {
      await api.logistics.dispatchVehicle(logisticsId, dispatchData)
      ElMessage.success('派车成功')
      fetchLogistics() // 刷新列表
    } catch (error) {
      ElMessage.error('派车失败')
    }
  }
  
  return {
    logistics,
    loading,
    fetchLogistics,
    getTrackingInfo,
    dispatchVehicle
  }
}

// ============ 数据分析示例 ============

/**
 * 仪表板数据示例
 */
export const useDashboard = () => {
  const dashboardData = ref(null)
  const loading = ref(false)
  
  const fetchDashboardData = async (period = 'week') => {
    loading.value = true
    try {
      dashboardData.value = await api.analytics.getDashboardOverview({ period })
    } catch (error) {
      ElMessage.error('获取仪表板数据失败')
    } finally {
      loading.value = false
    }
  }
  
  const fetchOrderTrends = async (params = {}) => {
    try {
      return await api.analytics.getOrderTrends(params)
    } catch (error) {
      ElMessage.error('获取订单趋势失败')
      return null
    }
  }
  
  onMounted(() => {
    fetchDashboardData()
  })
  
  return {
    dashboardData,
    loading,
    fetchDashboardData,
    fetchOrderTrends
  }
}

// ============ 综合使用示例 ============

/**
 * 创建订单的完整流程示例
 */
export const useCreateOrderFlow = () => {
  const { items, fetchItems } = useItemManagement()
  const { getAvailableStations } = useStationManagement()
  const { createOrder, calculatePrice } = useOrderManagement()
  
  const orderForm = reactive({
    items: [],
    pickupAddress: '',
    pickupTime: null,
    stationId: null,
    notes: ''
  })
  
  const estimate = ref(null)
  const submitting = ref(false)
  
  // 计算订单预估价格
  const updateEstimate = async () => {
    if (orderForm.items.length > 0) {
      estimate.value = await calculatePrice(orderForm.items)
    } else {
      estimate.value = null
    }
  }
  
  // 提交订单
  const submitOrder = async () => {
    submitting.value = true
    try {
      const response = await createOrder(orderForm)
      
      // 重置表单
      Object.assign(orderForm, {
        items: [],
        pickupAddress: '',
        pickupTime: null,
        stationId: null,
        notes: ''
      })
      
      estimate.value = null
      return response
    } finally {
      submitting.value = false
    }
  }
  
  return {
    items,
    orderForm,
    estimate,
    submitting,
    fetchItems,
    getAvailableStations,
    updateEstimate,
    submitOrder
  }
}

/**
 * 在组件中使用示例：
 * 
 * <script setup>
 * import { useItemManagement } from '@/api/examples'
 * 
 * const {
 *   items,
 *   loading,
 *   fetchItems,
 *   createItem
 * } = useItemManagement()
 * 
 * // 加载数据
 * onMounted(() => {
 *   fetchItems({ page: 1, pageSize: 10 })
 * })
 * 
 * // 创建新物品
 * const handleCreateItem = async () => {
 *   const success = await createItem({
 *     name: '新物品',
 *     category: '分类',
 *     unit: 'kg',
 *     pricePerUnit: 1.0,
 *     description: '描述'
 *   })
 *   
 *   if (success) {
 *     fetchItems() // 刷新列表
 *   }
 * }
 * </script>
 */
